<template>
  <Row class="iot-wrapper">
    <Row style="padding:10px 20px;font-size:14px;">
      <i-col span="16">
        <i-col span="12">
          <span class="label-span">所属企业：</span>
          <Select class="label-form" v-model="searchParams.companyId">
            <Option v-for="(item,index) in companyList" :value="item.id" :key="index">{{item.name}}</Option>
          </Select>
        </i-col>
        <i-col span="12">
          <span class="label-span">设备名称：</span>
          <Input class="label-form" v-model="searchParams.deviceName" clearable></Input>
        </i-col>
      </i-col>
      <i-col span="16" style="margin-top:14px;">
        <i-col span="12">
          <span class="label-span">所属产品：</span>
          <Select class="label-form" clearable v-model="searchParams.productKey" @on-change="handleTriggerChange">
            <Option v-for="(item, index) in productList" :key="index" :value="item.productKey">{{item.productName}}
            </Option>
          </Select>
        </i-col>
        <i-col span="12" v-if="!hideGateWay">
          <span class="label-span">所属网关：</span>
          <Select class="label-form" clearable v-model="searchParams.gatewayId">
            <Option v-for="(item, index) in gateWayList" :key="index" :value="item.id">{{item.deviceName}}</Option>
          </Select>
        </i-col>
      </i-col>
      <i-col span="16" style="margin-top:14px;">
        <span class="label-span">设备状态：</span>
        <RadioGroup v-model="searchParams.alarmStatus" type="button">
          <Radio :label="null">全部</Radio>
          <Radio :label="1">告警</Radio>
          <Radio :label="0">正常</Radio>
        </RadioGroup>
      </i-col>
      <i-col span="24" style="margin-top:14px;">
        <span class="label-span">是否在线：</span>
        <RadioGroup v-model="searchParams.status" type="button">
          <Radio :label="null">全部</Radio>
          <Radio label="ONLINE">在线</Radio>
          <Radio label="OFFLINE">离线</Radio>
          <Radio label="UNACTIVE">未激活</Radio>
          <Radio label="DISABLE">禁用</Radio>
        </RadioGroup>
      </i-col>
      <i-col span="6" style="margin-top:14px;">
        <Button type="primary" @click="handleSearch"> 查 询 </Button>
        <Button style="margin-left:15px;" type="primary" @click="handleNew">新增设备</Button>
      </i-col>
    </Row>
    <Col class="iot-wrapper-table" span="24">
    <Table :data="tableData" :columns="columns" border :loading="loading">
    </Table>
    </Col>
    <Col class="panel page-panel cf" style="margin-top:10px;">
    <Page :total="pageInfo.total" show-total :current.sync="pageInfo.page" class="fr" @on-change="switchThePaging"
      :page-size="20"></Page>
    </Col>
    <Modal v-model="visible" title="新建设备">
      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100">
        <FormItem label="所属企业：" prop="companyId">
          <Select v-model="formValidate.companyId" placeholder="请选择所属企业..." @on-change="handleCompanyChange">
            <Option v-for="(item,index) in companyList" :value="item.id" :key="index">{{item.name}}</Option>
          </Select>
        </FormItem>
        <FormItem label="所属区域：" prop="groupId">
          <Select v-model="formValidate.groupId" placeholder="请选择所属区域...">
            <Option v-for="item in groupList" :key="item.index" :value="item.groupId">{{item.groupName}}</Option>
          </Select>
        </FormItem>
        <FormItem label="所属产品：" prop="productKey">
          <Select class="label-form" clearable v-model="formValidate.productKey" @on-change="handleProductChange">
            <Option v-for="(item, index) in productList" :key="index" :value="item.productKey">{{item.productName}}
            </Option>
          </Select>
        </FormItem>
        <FormItem label="所属网关：" prop="parentId" v-if="!hideGateWay2">
          <Select class="label-form" clearable v-model="formValidate.parentId">
            <Option v-for="(item, index) in gateWayList2" :key="index" :value="item.id">{{item.deviceName}}</Option>
          </Select>
        </FormItem>
        <FormItem label="设备名称：" prop="nickName">
          <Input v-model="formValidate.nickName" placeholder="请输入设备名称..." clearable></Input>
        </FormItem>
        <FormItem label="设备ID：" prop="deviceName">
          <Input v-model="formValidate.deviceName" placeholder="请输入设备ID..."></Input>
        </FormItem>
        <FormItem label="设备位置：" prop="location">
          <Input v-model="formValidate.location" placeholder="请输入设备位置..."></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="visible=false">取消</Button>
        <Button @click="confirm" type="primary">确认</Button>
      </div>
    </Modal>
  </Row>
</template>
<script>
import {
  getIotDeviceList,
  getIotCompanyList,
  disableIotDevice,
  getIotProductList,
  getIotGateWayList,
  getIotGroupList,
  saveIotDevice,
  deleteIotDevice
} from '@/api'

import deviceDetail from './components/deviceDetail'
import tools from './tools'
const { genRuleValidate, genColumns } = tools
export default {
  components: { deviceDetail },
  async mounted() {
    await this.getCompanyList()
    await this.getProductionList()
    await this.init()
  },
  data() {
    const vm = this
    return {
      columns: genColumns(vm),
      ruleValidate: genRuleValidate(),
      hideGateWay: true,
      hideGateWay2: true,
      productList: [],
      loading: false,
      companyList: [],
      gateWayList: [],
      gateWayList2: [],
      groupList: [],
      searchParams: {
        companyId: '',
        deviceName: '',
        productKey: '',
        status: null,
        gatewayId: '',
        alarmStatus: null
      },
      visible: false,
      tableData: [],
      pageInfo: {
        page: 1,
        total: 0
      },
      selectRow: {},
      formValidate: {
        companyId: '',
        groupId: '',
        productKey: '',
        parentId: '',
        deviceName: '',
        nickName: '',
        location: ''
      }
    }
  },

  methods: {
    handleSearch() {
      this.init()
    },

    async init() {
      this.loading = true
      const params = {
        ...this.searchParams,
        page: this.pageInfo.page,
        size: 20
      }
      const { code, data } = await getIotDeviceList(params)
      if (code === 200) {
        const { list, total } = data
        this.tableData = list
        this.pageInfo.total = total
        this.loading = false
        return false
      }
      this.tableData = []
      this.loading = false
      this.pageInfo.total = 0
    },

    async getCompanyList() {
      const { code, data } = await getIotCompanyList()
      if (code === 200) {
        this.companyList = data
        return false
      }
      this.companyList = []
    },

    async handleDelete(row) {
      const { id } = row
      let { code } = await deleteIotDevice(id)
      if (code === 200) {
        this.init()
      } else {
        this.$Message.error('操作失败，请刷新重试！')
      }
    },

    async handleCheck(row) {
      this.selectRow = row
      this.visible = true
    },

    async switchThePaging(index) {
      this.pageInfo.page = index
      await this.init()
    },

    async handleCompanyChange(id) {
      await this.getGroupList(id)
    },

    async getGroupList(id) {
      const params = { companyId: id }
      const { code, data } = await getIotGroupList(params)
      if (code === 200) {
        this.groupList = data
      } else {
        this.groupList = []
      }
    },

    // 新建
    async handleNew() {
      const vm = this
      vm.visible = true
      this.$nextTick(() => {
        const formValidate = this.$refs.formValidate
        formValidate.resetFields()
        this.searchParams = {
          companyId: '',
          deviceName: '',
          productKey: '',
          status: null,
          gatewayId: '',
          parentId: '',
          alarmStatus: null
        }
      })
    },

    async getProductionList() {
      const params = { size: 100, page: 1 }
      const { code, data } = await getIotProductList(params)
      if (code === 200) {
        this.productList = data
        return false
      }
      this.productList = []
    },

    async handleTriggerChange(id) {
      this.gateWayList = []
      this.searchParams.gatewayId = ''
      const item = this.productList.find(t => t.productKey === id)
      if (item) {
        const { nodeType, productKey } = item
        // console.log(nodeType)
        if (nodeType === 0) {
          await this.getGatewayList(productKey)
          this.hideGateWay = false
        } else {
          this.hideGateWay = true
        }
      } else {
        this.hideGateWay = true
      }
    },

    // 新增 > 产品列表change
    async handleProductChange(id) {
      this.gateWayList2 = []
      this.formValidate.gatewayId = ''
      const item = this.productList.find(t => t.productKey === id)
      if (item) {
        const { nodeType, productKey } = item
        if (nodeType === 0) {
          const { code, data } = await getIotGateWayList({ productKey })
          if (code === 200) {
            this.gateWayList2 = data
          }
          this.hideGateWay2 = false
        } else {
          this.hideGateWay2 = true
        }
      } else {
        this.hideGateWay2 = true
      }
    },

    async getGatewayList(productKey) {
      const params = { productKey }
      const { code, data } = await getIotGateWayList(params)
      if (code === 200) {
        this.gateWayList = data
      } else {
        this.gateWayList = []
      }
    },

    /**
     * 禁用设备
     */
    async handleDisable(id) {
      const { code } = await disableIotDevice(id)
      if (code === 200) {
        this.init()
      }
    },

    /**
     * 启用设备
     */
    async handleEnable(id) {
      const { code } = await disableIotDevice(id)
      if (code === 200) {
        this.$Message.success('操作成功！')
        this.init()
      } else {
        this.$Message.error('未知错误，请稍后重试！')
      }
    },

    //
    async confirm() {
      this.$refs.formValidate.validate(async valid => {
        if (valid) {
          const params = { ...this.formValidate }
          const { code, message } = await saveIotDevice(params)
          if (code === 200) {
            this.visible = false
            this.init()
          } else {
            this.$Message.error(message)
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.iot-wrapper {
  background: #fff;
  overflow: auto;
  height: 100%;
  .label-span {
    display: inline-block;
    width: 75px;
  }
  .label-form {
    width: 300px !important;
    // width: calc(100% - 99px) !important;
  }
  &-table {
    box-sizing: border-box;
    padding: 10px;
  }
}
</style>
